<template>
    <view>
        <!-- pages/cart/cart.wxml -->
        <view class="address">
            <button @tap="chooseAddress">+添加收货地址</button>
            <view v-if="address" class="address-info">
                <text>收货人：{{ address.userName }}</text>
                <text>电话：{{ address.telNumber }}</text>
                <text>地址：{{ address.provinceName }} {{ address.cityName }} {{ address.countyName }} {{ address.detailInfo }}</text>
            </view>
        </view>
        <view class="line"></view>
        <view class="cart-list">
            <block v-for="(item, index) in cart" :key="index">
                <view class="cart-item">
                    <checkbox-group>
                        <label>
                            <checkbox :value="item.goods_id" :checked="item.checked" :data-index="index" @tap="checkboxChange" />
                        </label>
                    </checkbox-group>
                    <view class="image-box">
                        <image class="goods-image" :src="item.goods_small_logo" mode="aspectFill" @tap="onGoodsDetail" :data-gid="item.goods_id"></image>
                    </view>
                    <view class="goods-info">
                        <text class="goods-name" @tap="onGoodsDetail" :data-gid="item.goods_id">{{ item.goods_name }}</text>
                        <view class="goods-info-bottom">
                            <text class="goods-price">￥{{ item.goods_price }}</text>
                            <view class="quantity-control">
                                <button @tap="decreaseQuantity" :data-index="index">-</button>
                                <text class="cont">{{ item.goods_count }}</text>
                                <button @tap="increaseQuantity" :data-index="index">+</button>
                            </view>
                        </view>
                    </view>
                </view>
            </block>
        </view>
        <view class="bottom-box">
            <view class="bottom">
                <view class="select-all">
                    <checkbox-group @change="selectAllChange">
                        <label>
                            <checkbox :checked="isAllChecked" />
                            <text>全选</text>
                        </label>
                    </checkbox-group>
                </view>
                <view class="total-price">
                    <text class="price-start">
                        合计：
                        <text class="price">￥{{ totalPrice }}</text>
                    </text>
                    <text class="tips">包含运费</text>
                </view>
                <view class="settlement">
                    <button @tap="toPay">结算({{ checkedCount }})</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
// pages/cart/cart.js
export default {
    data() {
        return {
            cart: [],
            address: null,
            isAllChecked: '',
            checkedCount: '',
            totalPrice: ''
        };
    },
    onLoad: function () {
        this.loadCart();
    },
    onShow: function () {
        this.loadCart();
        this.updateCheckStatus();
    },
    methods: {
        chooseAddress: function () {
            let that = this;
            uni.chooseAddress({
                success: function (res) {
                    that.setData({
                        address: res
                    });
                },
                fail: function (err) {
                    console.error('选择地址失败', err);
                }
            });
        },

        loadCart: function () {
            let cart = uni.getStorageSync('cart') || [];
            this.setData({
                cart: cart.map((item) => {
                    item.checked = false;
                    return item;
                })
            });
        },

        decreaseQuantity: function (e) {
            let index = e.currentTarget.dataset.index;
            let cart = this.cart;
            if (cart[index].goods_count > 1) {
                cart[index].goods_count--;
                this.setData({
                    cart: cart
                });
                uni.setStorageSync('cart', cart);
                this.updateCheckStatus();
            } else {
                uni.showModal({
                    title: '提示',
                    content: '是否从购物车中移除该商品？',
                    success: (res) => {
                        if (res.confirm) {
                            cart.splice(index, 1);
                            this.setData({
                                cart: cart
                            });
                            uni.setStorageSync('cart', cart);
                        }
                    }
                });
            }
        },

        increaseQuantity: function (e) {
            let index = e.currentTarget.dataset.index;
            let cart = this.cart;
            cart[index].goods_count++;
            this.setData({
                cart: cart
            });
            uni.setStorageSync('cart', cart);
            this.updateCheckStatus();
        },

        onGoodsDetail: function (event) {
            const gid = event.currentTarget.dataset.gid;
            console.log('onGoodsDetail gid:', gid);
            uni.navigateTo({
                url: `/pages/goodsdetails/goodsdetails?gid=${gid}`
            });
        },

        selectAllChange: function (e) {
            let isAllChecked = e.detail.value.length > 0;
            let cart = this.cart.map((item) => {
                item.checked = isAllChecked;
                return item;
            });
            this.setData({
                cart: cart,
                isAllChecked: isAllChecked
            });
            uni.setStorageSync('cart', cart);
            this.updateCheckStatus();
        },

        checkboxChange: function (e) {
            const index = e.currentTarget.dataset.index;
            let cart = this.cart;
            cart[index].checked = !cart[index].checked;
            this.setData(
                {
                    cart: cart
                },
                () => {
                    this.updateCheckStatus();
                }
            );
        },

        updateCheckStatus: function () {
            let cart = this.cart;
            let checkedCount = 0;
            let totalPrice = 0;
            cart.forEach((item) => {
                if (item.checked) {
                    checkedCount++;
                    totalPrice += item.goods_price * item.goods_count;
                }
            });
            this.setData({
                checkedCount: checkedCount,
                totalPrice: totalPrice.toFixed(2)
            });
        },

        toPay: function () {
            let checkedGoods = this.cart.filter((item) => item.checked);
            let totalPrice = checkedGoods
                .reduce((total, item) => {
                    return total + item.goods_price * item.goods_count;
                }, 0)
                .toFixed(2);
            if (checkedGoods.length === 0) {
                uni.showToast({
                    title: '请选择商品',
                    icon: 'none'
                });
                return;
            }
            let addressInfo = JSON.stringify(this.address);
            let params = {
                goodsList: encodeURIComponent(JSON.stringify(checkedGoods)),
                totalPrice: totalPrice,
                addressInfo: encodeURIComponent(addressInfo)
            };
            uni.navigateTo({
                url: `/pages/pay/pay?goodsList=${params.goodsList}&totalPrice=${params.totalPrice}&addressInfo=${params.addressInfo}`
            });
        }
    }
};
</script>
<style>
/* pages/cart/cart.wxss */
.address {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 175rpx;
}
.line {
    width: 100%;
    height: 50rpx;
    background-color: rgb(243, 239, 239);
}
.cart-item {
    width: 100%;
    height: 250rpx;
    display: flex;
    align-items: center;
}
.image-box {
    width: 200rpx;
    height: 150rpx;
    margin-right: 25rpx;
}
.goods-image {
    width: 200rpx;
    height: 150rpx;
}
.quantity-control {
    display: flex;
    align-items: center;
}
.quantity-control button {
    padding: 0;
    margin: auto 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50rpx;
    height: 50rpx;
    border: black 1rpx solid;
    font-size: larger;
}
.cont {
    font-size: large;
}
.goods-info {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    height: 250rpx;
}
.goods-info-bottom {
    display: flex;
    justify-content: space-between;
}
.goods-price {
    font-size: larger;
    color: red;
}
.bottom-box {
    position: fixed;
    bottom: 0;
}
.bottom {
    display: flex;
    align-items: center;
}
.select-all {
    font-size: large;
}
.total-price {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 285rpx;
    margin-left: 135rpx;
}
.price-start {
    font-size: large;
}
.price {
    color: red;
}
.tips {
    color: gray;
}
.settlement button {
    font-size: larger;
    background-color: red;
    color: white;
    width: 200rpx;
    margin-left: 15rpx;
}
</style>
